package com.authine.cloudpivot.ext.service.impl;

import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.PlatformConst;
import com.authine.cloudpivot.ext.dto.system.OutApiClientDto;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsStatusEnum;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.ZhendeService;
import com.authine.cloudpivot.ext.utils.HttpClients;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.system.OutApiClientApiUtils;
import com.authine.cloudpivot.ext.vo.OrderResultModel;
import com.authine.cloudpivot.ext.vo.TempOrderReceiptVo;
import com.authine.cloudpivot.ext.vo.zhende.PushOrderModel;
import com.authine.cloudpivot.ext.vo.zhende.PushOrderUpdateModel;
import com.authine.cloudpivot.ext.vo.zhende.ZhenDeReceiptDTO;
import com.authine.cloudpivot.ext.vo.zhende.ZhenDeReceiptModel;
import com.authine.cloudpivot.ext.vo.zhende.order.EnvelopeOrder;
import com.authine.cloudpivot.ext.vo.zhende.receipt.EnvelopeReceipt;
import com.authine.cloudpivot.ext.vo.zhende.receipt.crm.SI1210MMPURCHASERECINFOReq;
import com.authine.cloudpivot.ext.vo.zhende.receipt.crm.SI1210MMPURCHASERECINFOReqService;
import com.authine.cloudpivot.ext.vo.zhende.receipt.s4.DT1210MMPURCHASERECINFOREQ;
import com.authine.cloudpivot.ext.vo.zhende.receipt.s4.DT1210MMPURCHASERECINFOResp;
import com.authine.cloudpivot.ext.vo.zhende.update.EnvelopeUpdate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class ZhendeServiceImpl extends ApplicationBaseService implements ZhendeService {
    private static OrderService orderService = new OrderServiceImpl();

    // 振德接口用户名
    public final static String ZHENDE_USERNAME = "OA2PO";
    // 振德接口密码
    public final static String ZHENDE_PASSWORD = "ZDPO2018";

    /**
     * 下订单
     *
     * @param pushOrderModel
     */
    @Override
    public String pushOrder(PushOrderModel pushOrderModel) {

        if (pushOrderModel == null) {
            return null;
        }
        EnvelopeOrder envelopeOrder = EnvelopeOrder.toXml(pushOrderModel);
        String returnXml = "";
        if (null != envelopeOrder) {
            String requestXml = "";
            try {
                requestXml = HttpClients.convertToXml(envelopeOrder);
                log.warn("推送下订单数据给振德请求参数：{}", requestXml);
            } catch (Exception e) {
                log.error("振德修改订单商品，错误信息：" + e +"入参："+pushOrderModel);
            }
            HashMap<String, String> param = new HashMap<>(1);
            param.put("SOAPAction", "http://sap.com/xi/WebService/soap1.1");
            param.put("Accept-Encoding", "gzip,deflate\n");
            param.put("Connection", "Keep-Alive");
//            param.put("Username", "OA2PO");
//            param.put("Password", "ZDPO2018");
            param.put("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
            param.put("Cookie", "com.sap.engine.security.authentication.original_application_url=POST#tx8VJXOB11jlpW9ZMb93O9B20d7q1sLTnpGM9GPz3rY0X2eKWHEqmCq%2FsewpX0G6C%2FVh2NX58RBu%2Fus%2FOhlc%2BRqQZkKAZ%2BGZKUPVS7Soq80U4HN1XLqbWJxK%2FRZl5aQIeOCLUnHhuQE607xZdNfMyb80Q6dSENSJdCxBGvUCNWIu3cNdoAhSO0MivLXpCDr44oAeEWvWlTVq3rgAxteQx3wjUUZAqNwGE4MCakXPhIAb%2B1pnr55HF6lM1axRrgg6QAuJkSa6I1pM6ADQa7cHkf%2Bth4ojpcG7cNbDngBhizY%3D; saplb_*=(J2EE13889320)13889351");
            param.put("Cookie2", "$Version=1");

            OutApiClientDto outApiClient = OutApiClientApiUtils.getByGomroUsername("punchout_zhende_order_create");
            //T0EyUE86WkRQTzIwMTg=
            param.put("Authorization", "Basic " + outApiClient.getAccess_token());

            String url = outApiClient.getResource_url();

            try {
                returnXml = HttpClients.sendZhenSyncRequest(requestXml, url, param);
            } catch (Exception e) {
                log.error("振德修改订单商品，错误信息：" + e +"入参："+pushOrderModel);
            }
            log.warn("推送下订单数据给振德返回参数：{}", returnXml);
        }
        return returnXml;
    }

    /**
     * 下订单后修改
     *
     * @param pushOrderUpdateModelList
     * @return
     */
    @Override
    public String pushOrderUpdate(List<PushOrderUpdateModel> pushOrderUpdateModelList) {
        EnvelopeUpdate envelopeUpdate = EnvelopeUpdate.toXml(pushOrderUpdateModelList);
        String returnXml = "";
        if (null != envelopeUpdate) {
            String requestXml = "";
            try {
                requestXml = HttpClients.convertToXml(envelopeUpdate);
                log.warn("振德修改订单商品数据请求参数：{}", requestXml);
            } catch (Exception e) {
                log.error("振德修改订单商品，错误信息：" + e +"入参："+StringUtils.collectionToCommaDelimitedString(pushOrderUpdateModelList));
            }
            HashMap<String, String> param = new HashMap<>(1);
            param.put("SOAPAction", "http://sap.com/xi/WebService/soap1.1");
            param.put("Accept-Encoding", "gzip,deflate\n");
            param.put("Connection", "Keep-Alive");
            param.put("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
            param.put("Cookie", "com.sap.engine.security.authentication.original_application_url=POST#tx8VJXOB11jlpW9ZMb93O9B20d7q1sLTnpGM9GPz3rY0X2eKWHEqmCq%2FsewpX0G6C%2FVh2NX58RBu%2Fus%2FOhlc%2BRqQZkKAZ%2BGZKUPVS7Soq80U4HN1XLqbWJxK%2FRZl5aQIeOCLUnHhuQE607xZdNfMyb80Q6dSENSJdCxBGvUCNWIu3cNdoAhSO0MivLXpCDr44oAeEWvWlTVq3rgAxteQx3wjUUZAqNwGE4MCakXPhIAb%2B1pnr55HF6lM1axRrgg6QAuJkSa6I1pM6ADQa7cHkf%2Bth4ojpcG7cNbDngBhizY%3D; saplb_*=(J2EE13889320)13889351");
            param.put("Cookie2", "$Version=1");

            OutApiClientDto outApiClient = OutApiClientApiUtils.getByGomroUsername("punchout_zhende_order_update");
            //T0EyUE86WkRQTzIwMTg=
            param.put("Authorization", "Basic " + outApiClient.getAccess_token());

            String url = outApiClient.getResource_url();

            try {
                returnXml = HttpClients.sendZhenSyncRequest(requestXml, url, param);
            } catch (Exception e) {
                log.error("振德修改订单商品，错误信息：" + e +"入参："+StringUtils.collectionToCommaDelimitedString(pushOrderUpdateModelList));
            }
            log.warn("振德修改订单商品数据返回参数：{}", returnXml);
        }
        return returnXml;
    }

    /**
     * 收货
     *
     * @param purchaseNumber
     * @return
     */
    @Override
    public String receiptOrderPush(String purchaseNumber) {
        if (purchaseNumber == null) {
            return null;
        }
        EnvelopeReceipt envelopeReceipt = EnvelopeReceipt.toXml(purchaseNumber);
        String returnXml = "";
        if (null != envelopeReceipt) {
            String requestXml = "";
            try {
                requestXml = HttpClients.convertToXml(envelopeReceipt);
            } catch (Exception e) {
                log.error("推送收货数据给振德返回，错误信息：" + e +"入参："+purchaseNumber);
            }
            HashMap<String, String> param = new HashMap<>(1);
            param.put("SOAPAction", "http://sap.com/xi/WebService/soap1.1");
            param.put("Accept-Encoding", "gzip,deflate\n");
            param.put("Connection", "Keep-Alive");
            param.put("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
            param.put("Cookie", "com.sap.engine.security.authentication.original_application_url=POST#tx8VJXOB11jlpW9ZMb93O9B20d7q1sLTnpGM9GPz3rY0X2eKWHEqmCq%2FsewpX0G6C%2FVh2NX58RBu%2Fus%2FOhlc%2BRqQZkKAZ%2BGZKUPVS7Soq80U4HN1XLqbWJxK%2FRZl5aQIeOCLUnHhuQE607xZdNfMyb80Q6dSENSJdCxBGvUCNWIu3cNdoAhSO0MivLXpCDr44oAeEWvWlTVq3rgAxteQx3wjUUZAqNwGE4MCakXPhIAb%2B1pnr55HF6lM1axRrgg6QAuJkSa6I1pM6ADQa7cHkf%2Bth4ojpcG7cNbDngBhizY%3D; saplb_*=(J2EE13889320)13889351");
            param.put("Cookie2", "$Version=1");

            OutApiClientDto outApiClient = OutApiClientApiUtils.getByGomroUsername("punchout_zhende_order_receipt");

            //T0EyUE86WkRQTzIwMTg=
            param.put("Authorization", "Basic " + outApiClient.getAccess_token());
            String url = outApiClient.getResource_url();

            try {
                returnXml = HttpClients.sendZhenSyncRequest(requestXml, url, param);
            } catch (Exception e) {
                log.error("推送收货数据给振德返回，错误信息：" + e +"入参："+purchaseNumber);
            }
            log.warn("推送收货数据给振德返回参数：{}", returnXml);
        }
        return returnXml;
    }

    @Override
   public ZhenDeReceiptModel receiptOrderPush1(String purchaseNumber) {

       DT1210MMPURCHASERECINFOREQ req = new DT1210MMPURCHASERECINFOREQ();
       req.setIVZEBELN(String.valueOf(purchaseNumber));
       log.info("req: {}", req.getIVZEBELN());

       Authenticator.setDefault(new Authenticator() {
           @Override
           protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(ZHENDE_USERNAME, ZHENDE_PASSWORD.toCharArray());
           }
       });

       SI1210MMPURCHASERECINFOReqService service = new SI1210MMPURCHASERECINFOReqService();
       SI1210MMPURCHASERECINFOReq r = service.getHTTPPort();

       Client client = ClientProxy.getClient(r);
       HTTPConduit http = (HTTPConduit) client.getConduit();
       AuthorizationPolicy authorizationPolicy = new AuthorizationPolicy();
       authorizationPolicy.setUserName(ZHENDE_USERNAME);
       authorizationPolicy.setPassword(ZHENDE_PASSWORD);
       authorizationPolicy.setAuthorizationType("Basic");
       http.setAuthorization(authorizationPolicy);

       DT1210MMPURCHASERECINFOResp resp = r.si1210MMPURCHASERECINFOReq(req);

       log.info("resp: {}", resp.getETZMMS045());

       List<DT1210MMPURCHASERECINFOResp.ETZMMS045> etzmms045 = resp.getETZMMS045();
       // 封装的 物料编号 未清数量集合
       List<HashMap<String, Object>> hashMapList = new ArrayList<>();

       List<ZhenDeReceiptDTO> zhenDeReceiptDTOList = new ArrayList<>();
       for (DT1210MMPURCHASERECINFOResp.ETZMMS045 et : etzmms045) {
           HashMap<String, Object> map = new HashMap<>(2);
           map.put("itemNumber", et.getZMATNR());
           map.put("num", et.getZCGWQQUANTITY());
           hashMapList.add(map);

           ZhenDeReceiptDTO zhenDeReceiptDTO = new ZhenDeReceiptDTO();
           zhenDeReceiptDTO.setZEBELN(et.getZEBELN());
           zhenDeReceiptDTO.setZMATNR(et.getZMATNR());
           zhenDeReceiptDTO.setZCG_WQ_QUANTITY(et.getZCGWQQUANTITY());
           zhenDeReceiptDTOList.add(zhenDeReceiptDTO);
       }


       log.info("map: {}", hashMapList);
       log.info("list: {}", zhenDeReceiptDTOList);
       if (ObjectUtils.isEmpty(etzmms045)) return null;

       ZhenDeReceiptModel zhenDeReceiptModel = new ZhenDeReceiptModel();
       zhenDeReceiptModel.setPo(etzmms045.get(0).getZEBELN());
       Set<String> s1 = new HashSet<>();
       zhenDeReceiptDTOList.forEach(t -> {
           String trim = t.getZCG_WQ_QUANTITY().trim();
           if (trim.equals("0.000")) {
               s1.add(t.getZMATNR());
           }
       });
       zhenDeReceiptModel.setItemNumber(s1);

       log.info("model-->{}", zhenDeReceiptModel);

       // 根据订单id获取到返回的物料编号 和 未清数量
       // 当未清数量为0的时候 然后去调用物料编号对应的商品 再去调用订单收货接口 把订单商品的状态改为已收货
       // todo jianzhou
       return zhenDeReceiptModel;
   }

    /**
     * 振德 定时任务回调批量收货
     * @param zhenDeReceiptModel
     * @return
     */
    @Override
    public TempOrderReceiptVo zhenDeGoodsReceiptBatch(ZhenDeReceiptModel zhenDeReceiptModel) {
        String po = zhenDeReceiptModel.getPo();
        Set<String> itemNumber = zhenDeReceiptModel.getItemNumber();
        if (Objects.isNull(zhenDeReceiptModel) || com.authine.cloudpivot.ext.utils.StringUtils.isBlank(zhenDeReceiptModel.getPo())) {
            return null;
        }
        log.info("po:--{}, number:--{}", po, itemNumber);
        if (itemNumber == null || itemNumber.isEmpty()) {
            log.warn("sku为null!");
            return null;
        }
        List<Map<String, Object>> goodsEntityList;
        if (CollectionUtils.isNotEmpty(zhenDeReceiptModel.getItemNumber())) {
            goodsEntityList = listOrderGoodsByErpPOSku(zhenDeReceiptModel.getPo(), zhenDeReceiptModel.getItemNumber());
        } else {
            goodsEntityList = listOrderGoodsByErpPO(zhenDeReceiptModel.getPo());
        }

        if (null == goodsEntityList || goodsEntityList.isEmpty()) {
            log.warn("未查询到相关订单商品!");
            return null;
        }
        List<String> orderCustomerGoodsIds = goodsEntityList.stream().map(t->(String) t.get("id")).collect(Collectors.toList());
        TempOrderReceiptVo result = orderService.goodsReceiptBatch(orderCustomerGoodsIds);
        return result;
    }

    @Override
    public OrderResultModel XmlToObject(String xml) {
        OrderResultModel orderResultModel = new OrderResultModel();
        if (xml.indexOf("<EV_EBELN>") != -1 && xml.indexOf("</EV_EBELN>") != -1) {
            String ebebeln = xml.substring(xml.indexOf("<EV_EBELN>") + 10, xml.indexOf("</EV_EBELN>"));
            log.warn("ebebeln：" + ebebeln);
            orderResultModel.setEvebeln(ebebeln);

        }
        if (xml.indexOf("<EV_MESS>") != -1 && xml.indexOf("</EV_MESS>") != -1) {
            String evmess = xml.substring(xml.indexOf("<EV_MESS>") + 9, xml.indexOf("</EV_MESS>"));
            log.warn("evmess：" + evmess);
            orderResultModel.setEvmess(evmess);
        }

        if (xml.indexOf("<EV_TYPE>") != -1 && xml.indexOf("</EV_TYPE>") != -1) {
            String evtype = xml.substring(xml.indexOf("<EV_TYPE>") + 9, xml.indexOf("</EV_TYPE>"));
            log.warn("evtype：" + evtype);
            orderResultModel.setEvtype(evtype);
        }

        if (xml.indexOf("<MESSAGEID>") != -1 && xml.indexOf("</MESSAGEID>") != -1) {
            String messageid = xml.substring(xml.indexOf("<MESSAGEID>") + 11, xml.indexOf("</MESSAGEID>"));
            log.warn("messageid：" + messageid);
            orderResultModel.setMessageid(messageid);
        }
        return orderResultModel;
    }

    /**
     * 获取振德所有待收货商品的订单ERP PO
     * @return
     */
    @Override
    public List<String> getErpPoByZhenDeToReceive() {
        List<Map<String, Object>> erpPOs = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("distinct(id) as id")
                .notEq("erp_po", "xinjidi").eq("order_customer_goods_status", OrderGoodsStatusEnum.DoneDelivery.name())
                .in("customer_organization_name", PlatformConst.ZHENDE_ORGANIZATION_NAMES).queryForList();
        return erpPOs.stream().filter(t->!Objects.isNull(t.get("id"))).map(t->(String)t.get("id")).collect(Collectors.toList());
    }

    /**
     * 根据erppo和客户物料查询订单商品id
     *
     * @param erpPo
     * @param customerSku
     * @return
     */
    public List<Map<String, Object>> listOrderGoodsByErpPOSku(String erpPo, Set<String> customerSku) {
        List<Map<String, Object>> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("*").eq("erp_po", erpPo)
                .in("sku", customerSku).queryForList();
        return orderCustomerGoods;
    }

    /**
     * 根据erppo查询订单商品id
     *
     * @param erpPo
     * @return
     */
    public List<Map<String, Object>> listOrderGoodsByErpPO(String erpPo) {
        List<Map<String, Object>> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("*").eq("erp_po", erpPo)
                .queryForList();
        return orderCustomerGoods;
    }
}
